package com.tanguy.user.ui.me.activity.account

import android.widget.TextView
import cn.sinata.xldutils_kotlin.rxutils.ResultException
import cn.sinata.xldutils_kotlin.utils.SpanBuilder
import com.tanguy.user.App.Companion.app
import com.tanguy.user.R
import com.tanguy.user.base.ImmersionTitleActivity
import com.tanguy.user.net.http.HttpManager
import com.tanguy.user.utlis.extend.*
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import org.jetbrains.anko.find

/**
 * Created by dab on 2017/10/10 0010 09:30
 * 更换手机
 */
class ChangePhoneActivity : ImmersionTitleActivity() {
    override fun setContentViewRes(): Int = R.layout.activity_change_phone
    private lateinit var mCaptcha: TextView
    private lateinit var countDownTimer: Disposable

    override fun initView() {
        super.initView()
        title = "更换手机"
        mCaptcha = find(R.id.tv_captcha)
        SpanBuilder("ada")
    }


    override fun initEvent() {
        super.initEvent()
        click(R.id.tv_captcha) { getCaptcha() }
        click(R.id.tv_next) {
            val phoneNew = getEditTextString(R.id.et_phone_new)
            val phoneOld = getEditTextString(R.id.et_phone_old)
            val captcha = getEditTextString(R.id.et_captcha)
            if (!checkPhoneNumber(phoneNew)) return@click
            if (!checkPhoneNumber(phoneOld)) return@click
            if (phoneNew == phoneOld) {
                showToast("新手机号和原手机号相同")
                return@click
            }
            if (!checkCaptcha(captcha)) return@click
            HttpManager.yzCode(phoneNew, 3, captcha)
                    .flatMap {
                        if (it.code == 0) {
                            HttpManager.replacePhone(phoneOld, phoneNew)
                        } else {
                            Observable.error(ResultException(it.code, it.msg))
                        }
                    }.requestSucceed(this) {
                showToast("修改手机成功")
                app.user.phone = phoneNew
                finish()
            }

        }
    }

    private fun getCaptcha() {
        val phoneNew = getEditTextString(R.id.et_phone_new)
        if (!checkPhoneNumber(phoneNew)) return
        HttpManager.sendSmsCode(phoneNew, 3)
                .requestSucceed(this) {
                    // 获取验证码
                    countDownTimer = captchaCountDownTimer { finish, msg ->
                        mCaptcha.isClickable = finish
                        mCaptcha.text = msg
                    }
                }


    }
}